<?php
/**
 * Copyright (c) 2006, PORTALIER Julien
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @package      Feather PHP
 * @subpackage   Database
 * @copyright    Copyright (c) 2006, Julien PORTALIER
 * @link         http://feather.portalier.com
 * @license      http://www.opensource.org/licenses/mit-license.php The MIT License
 */

define('Q_PROCESS_NONE', false);
define('Q_PROCESS_FULL', 1);
define('Q_PROCESS_LITE', 2);
define('Q_PROCESS_LIST', 3);

abstract class db_base extends Base
{
	protected $conf;
	protected $operators;
	protected $link   = null;
	protected $debugs = array();
	
	function __construct($conf)
	{
		$this->conf = $conf;
#		$this->tablePrefix = $conf['prefix'];
	}
	
	abstract protected function __start();
	abstract protected function __stop();
	abstract protected function error($sql=null);
	
	abstract function & listFields($table);
	abstract function transactions($com, $v=null);
	abstract function execute($sql);
	abstract function & query($sql, $process=true, $tableName=0);
	abstract function getLastInsertID();
	
	abstract function field($f);
	abstract function value($v);
	abstract function limit($limit, $page=1);
	
	function conditions($conditions, $operator='AND')
	{
		if (empty($conditions))
			return;
		
		if (is_array($conditions))
		{
			if (!$this->link)
				$this->__start();
			$fields = array();
			
			foreach ($conditions as $f => $values)
			{
				if (!is_array($values)) $values = array($values);
				$f = $this->field($f);
				
				foreach ($values as $v)
				{
					if (strpos($v, '-! ') === 0)
					{
						// do not process value
						$v = str_replace('-! ', '', $v);
						$field = "$f $v";
					}
					else
					{
						if (!preg_match("/^({$this->operators}) .+/i", $v))
						{
							// no operator specified
							$oper = '=';
						}
						else
						{
							// operator specified
							list($oper, $v) = explode(' ', $v, 2);
						}
						$v = $this->value($v);
						$field = "$f $oper $v";
					}
					array_push($fields, $field);
				}
			}
			return 'WHERE '.implode(" $operator ", $fields);
		}
		return "WHERE $conditions";
	}
	
	function fields($fields)
	{
		if (!is_array($fields))
			$fields = explode(',', $fields);
		
		$_f = array();
		
		foreach ($fields as $f)
			array_push($_f, $this->field($f));
		
		return implode(', ', $_f);
	}
	
	function values(array $values)
	{
		$arr = array();
		foreach($values as $k => $v)
			$arr[$k] = $this->value($v);
		return implode(', ', $arr);
	}
	
	function order($order, $type='ORDER')
	{
		if (!preg_match('/(ORDER|GROUP) BY /', $order))
		{
			$order = preg_replace_callback('/([\w.]+)\s*(ASC|DESC|)[\s,]*/', array($this, '__preg_order'), $order);
			$order = "$type BY $order";
		}
		return $order;
	}
	
	function groupby($groupby)
	{
		return $this->order($groupby, 'GROUP');
	}
	
	protected function __preg_order($m)
	{
		return str_replace($m[1], $this->field($m[1]), $m[0]);
	}
}
?>